/*	talmud - The TALMUD roguelike
 * Copyright (C) 2012, talmud contributors
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of Version 2 of the GNU General Public License as published
 *  by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *  FITNESS FOR A PARTICULAR PURPOSE. See Version 2 of the GNU General Public
 *  License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "rand.h"

// linear distribution
uint32_t rn1(int32_t max)
{
	if (max <= 0)
	{
		return 0;
	}
	return rand() % max;
}

// exponentially bottom-weighted distribution
uint32_t rn2(int32_t max)
{
	uint32_t current;
	uint32_t roll;

	if (max <= 0)
	{
		return 0;
	}
	for (current = 0; current < max - 1; current++)
	{
		roll = rand() % (current + 2);
		if (!roll)
		{
			return current;
		}
	}

	return max - 1;
}

// linearly bottom-weighted distribution
uint32_t rn3(int32_t max)
{
	uint32_t current;
	uint8_t roll;
	uint8_t shifts;
	uint8_t idx;

	if (max <= 0)
	{
		return 0;
	}
	current = rand() % max;
	shifts = log2(max);
	for (idx = 0; idx <= shifts; idx++)
	{
		if (!current)
		{
			break;
		}
		roll = rand() % 4;
		if (!roll)
		{
			current--;
		}
	}

	return current;
}
